package wty.web.mvc.controller;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FlowController {
	private Map<String,String>                    flowPageMap      = new HashMap<String, String>();
	private Map<String,Class<? extends FlowPage>> flowPageClassMap = new HashMap<String, Class<? extends FlowPage>>();
	public void setFlowPageMap(Map<String, String> flowPageMap) {
		if(flowPageMap!=null) {
			this.flowPageMap.putAll(flowPageMap);
		}
	}
	
	@SuppressWarnings("unchecked")
	private Class<? extends FlowPage> getFlowPageClass(String flowPageKey) {
		if(flowPageKey!=null) {
			Class<? extends FlowPage> flowPageClass = flowPageClassMap.get(flowPageKey);
			if(flowPageClass==null) {
				String className = flowPageMap.get(flowPageKey);
				if(className!=null) {
					try {
						flowPageClass = (Class<? extends FlowPage>)Class.forName(className);
					} catch (ClassNotFoundException e) {
						flowPageMap.remove(flowPageKey);
						e.printStackTrace();
					}
				}
			}
			return flowPageClass;
		}
		return null;
	}
	private FlowPage newFlowPage(String flowPageKey) {
		Class<? extends FlowPage> flowPageClass = getFlowPageClass(flowPageKey);
		if(flowPageClass!=null) {
			try {
				return flowPageClass.newInstance();
			} catch (InstantiationException e) {
				flowPageMap.remove(flowPageKey);
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				flowPageMap.remove(flowPageKey);
				e.printStackTrace();
			}
		}
		return null;
	}
	public String execute(HttpServletRequest request, HttpServletResponse response) {
		String flowPageKey = "";
		
		FlowPage flowPage = newFlowPage(flowPageKey);
		if(flowPage!=null) {
			flowPage.init();
			return flowPage.getPage();
		}
		
		return null;
	}
}

abstract class FlowPage {
	protected HttpServletRequest request;
	protected HttpServletRequest response;
	public abstract String  getPage();
	public abstract void    init();
	public abstract boolean validate();
}